
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <termios.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdint.h>
#define DEV_UART 			"/dev/ttyUSB0"

struct env_info
{
	uint8_t head[3];	    //标识位st:
	uint8_t type;		    //数据类型
	uint8_t snum;		    //仓库编号
	uint8_t temp[2];	    //温度	
	uint8_t hum[2];		    //湿度
	uint8_t x;			    //三轴信息
    uint8_t y;
    uint8_t z;
	uint32_t ill;		    //光照
	uint32_t bet;           //电池电量
	uint32_t adc;           //电位器信息
};
struct conver_env_info {
    int snum;               //仓库编号
    float temperature;      //温度
    float humidity;         //湿度
    float ill;              //光照
    float bet;              //电池电量
    float adc;              //电位器信息
    
    signed char x;          //三轴信息
    signed char y;			 
    signed char z;			 
};
static float dota_atof (char unitl)
{
    if (unitl > 100)
    {
        return unitl / 1000.0;
    }
    else if (unitl > 10)
    {
        return unitl / 100.0;
    }
    else
    {
        return unitl / 10.0;
    }
}
void serial_init(int fd)
{
    struct termios options;
    tcgetattr(fd, &options);
    options.c_cflag |= ( CLOCAL | CREAD );
    options.c_cflag &= ~CSIZE;
    options.c_cflag &= ~CRTSCTS;
    options.c_cflag |= CS8;
    options.c_cflag &= ~CSTOPB;
    options.c_iflag |= IGNPAR;
    options.c_iflag &= ~(ICRNL | IXON);
    options.c_oflag = 0;
    options.c_lflag = 0;

    cfsetispeed(&options, B115200);
    cfsetospeed(&options, B115200);
    tcsetattr(fd,TCSANOW,&options);
}

static float dota_adc (unsigned int ratio)
{
    return ((ratio * 3.3) / 1024);
}

int main(int argc, char *argv[])
{
	unsigned char check[10];
	struct env_info envinfo;
    int ret;
	struct conver_env_info env_msg;
	int dev_uart_fd;
	
    if ((dev_uart_fd = open (DEV_UART, O_RDWR)) < 0)
    {
        perror ("open uart err");
        return -1;
    }
	
	serial_init (dev_uart_fd);
	while(1){
        ret = read(dev_uart_fd, &envinfo, sizeof(struct env_info));
        if(ret != sizeof(envinfo)){
            continue;
        }

        env_msg.x = envinfo.x;
        env_msg.y = envinfo.y;
        env_msg.z = envinfo.z;
        env_msg.temperature = envinfo.temp[0] + dota_atof(envinfo.temp[1]);
        env_msg.humidity = envinfo.hum[0] + dota_atof(envinfo.hum[1]);
        env_msg.ill = envinfo.ill;
        env_msg.bet = dota_adc(envinfo.bet);
        env_msg.adc = dota_adc(envinfo.adc);
		
		sleep(1);
		// printf("ill:%f\n",env_msg.ill);
        printf("x:%c y:%c z:%c temp:%.2f hum:%.2f ill:%.2f bet:%.2f adc:%.2f\n",env_msg.x,env_msg.y,env_msg.z,env_msg.temperature,env_msg.humidity,env_msg.ill,env_msg.bet,env_msg.adc);
    }

}
